package org.itboys.weixin.tools;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.PartSource;
import org.apache.commons.io.IOUtils;
import org.itboys.weixin.constant.WeixinConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 微信上传多媒体相关
 * @author ChenJunhui
 *
 */
public class WeixinMediaUtils {
	
	private static  Logger logger = LoggerFactory.getLogger(WeixinSendUtils.class);
	
	public static final int MAX_IMAGE_SIZE=128*1024;//微信允许的 最大的图片尺寸 128K
	
	/**
	 * 把页面上传的文件传给微信
	 * @param appId
	 * @param appSecret
	 * @param mediaType
	 * @param fileItem
	 * @return
	 */
	public static int sendMedia(String appId,String appSecret,String mediaType,FileItem fileItem){
		try {
			return WeixinMediaUtils.sendMedia(appId, appSecret, mediaType, fileItem.getSize(), fileItem.getName(), fileItem.getInputStream());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 把文件同步到微信
	 * @param appId
	 * @param appSecret
	 * @param mediaType
	 * @param fileSize
	 * @param fileName
	 * @param inputStream
	 * @return
	 */
	public static int sendMedia(String appId,String appSecret,String mediaType,final long fileSize,final String fileName,final InputStream inputStream){
		String accessToken = WeixinUtils.getAccessToken(appId, appSecret);
		PostMethod postMethod = new PostMethod(WeixinConstants.URL.UPLOAD_MEDIA_URL.replace("{0}", accessToken).replace("{1}", mediaType)+accessToken);
		RequestEntity  requestEntity = null;
		try{
					Part[] part = { new FilePart(fileName, new PartSource() {
						
						@Override
						public long getLength() {
							return fileSize;
						}
						
						@Override
						public String getFileName() {
							return fileName;
						}
						
						@Override
						public InputStream createInputStream() throws IOException {
							return inputStream;
						}
					}) };
			requestEntity = new MultipartRequestEntity(part, postMethod.getParams());
			postMethod.setRequestEntity(requestEntity);  
			HttpClient httpclient = HttpHelper.getHttpClient();
			 int statusCode = httpclient.executeMethod(postMethod);
			 if (statusCode != HttpStatus.SC_OK) {
		    	 logger.error("sendMedia error appId={} appSecret={}",appId,appSecret);
		    	 return -1;
		    }
			String sendResult = postMethod.getResponseBodyAsString();
			System.out.println(sendResult);
			return 1;
		}catch(Exception e){
			logger.error("sendMedia Exception appId="+appId+",appScret="+appSecret+",mediaType="+mediaType,e);
			return 0;
		}finally{
			if(postMethod!=null){
				postMethod.releaseConnection();
			}
			IOUtils.closeQuietly(inputStream);
		}
	}
}
